import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useAdminStore } from '@/store';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

const { protocol } = document.location;
let baseUrl = '';
if (import.meta.env.VITE_API_BASE_URL) {
  // axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
  baseUrl = import.meta.env.VITE_API_BASE_URL;
  // axios.defaults.baseURL = `${protocol}${baseUrl}`;
}

// 创建 axios 实例
const service = axios.create({
  baseURL: `${protocol}${baseUrl}`,
  timeout: 50000,
  headers: {'Content-Type': 'application/json;charset=utf-8'},
});

// 添加请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
      config.headers.token = token;
      config.headers.sourceUi = 'arco-design';
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    // code 为 200 才会执行下面代码
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200 || res.status === 0) {
      Message.error({
        content: res.msg || 'Error',
        duration: 5 * 1000,
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [401, 50008, 50012, 50014].includes(res.code) &&
        response.config.url !== '/adminapi/admin/info'
      ) {
        Modal.error({
          title: 'Confirm logout',
          content: 'You have been logged out, you can cancel to stay on this page, or log in again',
          okText: 'Re-Login',
          async onOk() {
            const adminStore = useAdminStore();

            await adminStore.logout();
            window.location.reload();
          },
        });
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  (error) => {
    const res = error.response.data;
    if (res.code === 401) {
      Modal.error({
        title: '确认退出',
        content: '登录已过期，请重新登录',
        okText: '重新登录',
        async onOk() {
          const adminStore = useAdminStore();
          await adminStore.logout();
          window.location.reload();
        },
      });
    } else {
      Message.error({
        content: error.msg || 'Request Error',
        duration: 5 * 1000,
      });
    }
    // Message.error({
    //   content: error.msg || 'Request Error',
    //   duration: 5 * 1000,
    // });
    // if (error.msg) {
    //   const adminStore = useAdminStore();
    //   adminStore.logout();
    //   setTimeout(() => {
    //     window.location.reload();
    //   }, 5000);
    // }

    return Promise.reject(error);
  }
);

export default service;